import { UploadApiResult } from './model/uploadModel';
import { defHttp } from '@/utils/http/axios';
import { UploadFileParams } from '#/axios';
import { useGlobSetting } from '@/hooks/setting';
import { AxiosProgressEvent } from 'axios';
import {useMessage} from "@/hooks/web/useMessage";

const { uploadUrl = '' } = useGlobSetting();

/**
 * @description: Upload interface
 */
export function uploadApi(
  params: UploadFileParams,
  onUploadProgress: (progressEvent: AxiosProgressEvent) => void,
) {
  return new Promise((resolve, reject) => {
    defHttp
      .uploadFile<UploadApiResult>(
        {
          url: uploadUrl,
          onUploadProgress,
          timeout: 60 * 1000,
        },
        params,
      )
      .then(async (res) => {
        const {
          // @ts-ignore
          data: { code, msg = '', result },
        } = res
        if (0 != code) {
          const { createMessage } = useMessage()
          createMessage.error(msg ? msg : '上传失败！')
          reject(res)
        } else {
          resolve(result)
        }
      })
      .catch((e) => {
        reject(e)
      })
      .finally(() => {
        resolve({})
      })
  })
}
